package forms;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import db.DbConnectionPool;
import db.DbException;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class formLogin extends ActionForm {
	private static final long serialVersionUID = 1L;
	private String loginName = null;
	private String pw = null;

	public String getLogin() {
		return loginName;
	}

	public String getPw() {
		return pw;
	}

	/**
	 * Validate the input data. If validation fails, then report the errors in
	 * students.jsp, and specifically where <html:errors/> is located.
	 * 
	 * @param mapping
	 *            The mapping used to select this instance
	 * @param request
	 *            The servlet request we are processing
	 */
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {

		ActionErrors errors = new ActionErrors();
		if (loginName == null)
			errors.add("firstMsgTag1", new ActionMessage(
					"errors.username.required"));
		else if (pw == null)
			errors.add("secondMsgTag2", new ActionMessage(
					"errors.password.required"));

		try {
			Connection conn = DbConnectionPool.getConnection();
			String selectAcct = "SELECT user_id FROM users WHERE user_name='"
					+ loginName + "'AND" + "password='md5(" + pw + ")'";
			// Create the statement
			PreparedStatement pStmt = conn.prepareStatement(selectAcct);

			// Use the created statement to SELECT
			// the student attributes FROM the Student table.
			ResultSet allStudents = pStmt.executeQuery();
			if (allStudents.next()) {
				errors.add("thirdMsgTag3", new ActionMessage(
						"errors.logon.invalid"));
			}
			allStudents.close();
			pStmt.close();
			conn.close();
		} catch (SQLException ex) {
			try {
				throw new DbException(ex);
			} catch (DbException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (NamingException ex) {
			try {
				throw new DbException(ex);
			} catch (DbException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return errors;

	}

}
